package StudyCode.summary.zipfile;

import java.io.*;
import java.nio.charset.Charset;
import java.util.zip.GZIPOutputStream;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class CompressDataStreamWithGzip {
	private static final int BYTE_BUFFER = 1024;
	private static final String GZIP_FILE_SUFFIX = ".gz";

	public static void gzip(InputStream is, OutputStream os)
			throws IOException {
		GZIPOutputStream gos = new GZIPOutputStream(os);

		byte[] data = new byte[BYTE_BUFFER];
		int length = -1;
		while ((length = is.read(data)) != -1) {
			gos.write(data, 0, length);
		}
		gos.finish();
		gos.flush();
		gos.close();
	}


	public static byte[] gzip(byte[] content) throws IOException {
		ByteArrayInputStream bis = new ByteArrayInputStream(content);
		ByteArrayOutputStream bos = new ByteArrayOutputStream();

		gzip(bis, bos);

		bos.flush();
		byte[] result = bos.toByteArray();
		bos.close();
		bis.close();

		return result;
	}


	public static byte[] gzip(String content) throws IOException {
		return gzip(content, Charset.forName("UTF-8"));
	}


	public static byte[] gzip(String content, Charset cs)
			throws IOException {
		ByteArrayInputStream bis = new ByteArrayInputStream(
				content.getBytes(cs));
		ByteArrayOutputStream bos = new ByteArrayOutputStream();

		gzip(bis, bos);

		bos.flush();
		byte[] result = bos.toByteArray();
		bos.close();
		bis.close();

		return result;
	}


	public static boolean gzip(File sourceFile) {
		return gzip(sourceFile, true);
	}


	public static boolean gzip(File sourceFile, boolean deleteSourceFile) {
		File gzipFile = new File(sourceFile.getParent(),
				sourceFile.getName() + GZIP_FILE_SUFFIX);
		return gzip(sourceFile, gzipFile, deleteSourceFile);
	}

	public static boolean gzip(File sourceFile, File gzipFile,
	                           boolean deleteSourceFile) {
		BufferedInputStream bis = null;
		try {
			bis = new BufferedInputStream(new FileInputStream(sourceFile));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		}

		BufferedOutputStream bos = null;
		try {
			bos = new BufferedOutputStream(new FileOutputStream(gzipFile));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			try {
				if (bis != null)
					bis.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			return false;
		}

		GZIPOutputStream gos = null;
		try {
			gos = new GZIPOutputStream(bos);
			byte[] data = new byte[BYTE_BUFFER];
			int length = -1;
			while ((length = bis.read(data)) != -1) {
				gos.write(data, 0, length);
			}
			gos.flush();
			gos.finish();
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} finally {
			try {
				if (gos != null)
					gos.close();
				if (bos != null)
					bos.close();
				if (bis != null)
					bis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		if (deleteSourceFile)
			return sourceFile.delete();

		return true;
	}
}
